import { forEach, map, uniq, uniqBy, filter, forIn } from "lodash";

export const getColumns = (value: any) => {
  const params: string[] = ["time"];
  forEach(value, (item, index) => {
    forEach(item.data, (it, i) => {
      params.push(it.title);
    });
  });
  const columns = map(uniq(params), (K) => {
    return {
      title: K === "time" ? "时间" : K,
      dataIndex: K,
      key: K,
    };
  });
  return columns;
};

export const getParamsData = (value: any, chart: any) => {
  let params: any[] = [{ title: "time", name: "time", type: "Field" }];
  forEach(chart, (item, index) => {
    forEach(item.data, (it, i) => {
      if (it.paramType === "Field") {
        params.push({ title: it.title, name: it.title, type: it.paramType });
      } else {
        params.push({
          title: it.title,
          name: it.expression,
          type: it.paramType,
        });
      }
    });
  });
  params = uniqBy(params, "title");
  let data: any = {};
  if (value.startTime === "") {
    data = value.data;
  } else {
    forEach(Object.keys(value.data), (k) => {
      if (value.data[k].length > 0) {
        data[k] = filter(value.data[k], (t) => {
          return t.systime >= value.startTime && t.systime <= value.endTime;
        });
      } else {
        data[k] = [];
      }
    });
  }

  // 查询最大数据的参数
  let p: string = "",
    length: number = 0;
  forIn(data, (v, k) => {
    if (v.length >= length) {
      (p = k), (length = v.length);
    }
  });
  const ParamsTime = map(data[p], (k) => {
    return k.systime;
  });
  data = { ...data, time: ParamsTime };
  const paramsList: any = [];
  for (let i = 0; i <= data[p].length; i++) {
    const tableItem: any = {};
    forEach(params, (item, index) => {
      tableItem.key = i;
      if (item.type === "Field") {
        if (item.title === "time") {
          tableItem.time = ParamsTime[i];
        } else if (data[item.title].length === 0) {
          tableItem[item.title] = "";
        } else {
          tableItem[item.title] =
            data[item.title] &&
            data[item.title][i] &&
            data[item.title][i][item.title];
        }
      } else {
        if (data[item.name].length === 0) {
          tableItem[item.title] = "";
        } else {
          tableItem[item.title] =
            data[item.name] &&
            data[item.name][i] &&
            data[item.name][i][item.name];
        }
      }
    });
    if (tableItem.time) {
      paramsList.push(tableItem);
    }
  }
  return paramsList;
};

export const sleep = (numberMillis: number) => {
  let now = new Date();
  const exitTime = now.getTime() + numberMillis;
  while (true) {
    now = new Date();
    if (now.getTime() > exitTime) return;
  }
};
